package com.mediacloud.app.newsmodule.fragment.baoliao.api;


import android.util.Log;
import android.webkit.URLUtil;

import com.mediacloud.app.newsmodule.fragment.baoliao.model.LocalMediaWithState;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.SubmitImageReturnData;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.user.net.AppfacUserSDK;
import com.mediacloud.app.user.net.SSLSocketClient;
import com.mediaclound.appfactnet.utils.GETBadInterceptor;
import com.mediacloud.app.util.ProxyUtil;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.X509TrustManager;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;

public class CMSApi {
public static final String SSP_ID="1";
    static BLApi blApi;

    public synchronized static void init() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.dns(new MyDns());
        ProxyUtil.config(builder);
        builder.protocols(Collections.unmodifiableList(Arrays.asList(Protocol.HTTP_1_1, Protocol.HTTP_2)));
        builder.readTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        builder.addInterceptor(new AdApiInterceptor());

        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), (X509TrustManager) SSLSocketClient.getTrustManager()[0]);
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.connectTimeout(HTTPClient.TIME_OUT, TimeUnit.SECONDS);
        if(URLUtil.isNetworkUrl(AppFactoryGlobalConfig.getAppServerConfigInfo(AppfacUserSDK.application).cms)==false)
        {
            Log.w("APPTAG","爆料后台接口地址没有配置");
            AppFactoryGlobalConfig.getAppServerConfigInfo(AppfacUserSDK.application).cms+="http://appfac/"+AppFactoryGlobalConfig.getAppServerConfigInfo(AppfacUserSDK.application).cms;
        }
        builder.addInterceptor(new GETBadInterceptor(AppFactoryGlobalConfig.getAppServerConfigInfo(AppfacUserSDK.application).cms,AppFactoryGlobalConfig.getAppServerConfigInfo(AppfacUserSDK.application).cdn_cms));
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppFactoryGlobalConfig.getAppServerConfigInfo(AppfacUserSDK.application).cms + "/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        if (blApi != null) {
            blApi = null;
        }
        blApi = retrofit.create(BLApi.class);
    }

    public static BLApi getBlApi() {
        synchronized (CMSApi.class) {
            if (blApi == null)
                init();
        }
        return blApi;
    }


    public interface BLApi {

        /**
         * 多文件上传图片
         *
         * @param parts
         * @return
         */
        @Multipart
        @POST("api/revelation/uploadImg")
        Call<SubmitImageReturnData> uploadImg(@PartMap Map<String, RequestBody> map, @Part List<MultipartBody.Part> parts);


        /**
         * 多图上传图片
         *
         * @param parts
         * @return
         */
        @Multipart
        @POST("/api/image/uploadImage")
        Call<SubmitImageReturnData> multiImageupload(@PartMap Map<String, RequestBody> map, @Part List<MultipartBody.Part> parts);

    }

    public static List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }

    public static List<MultipartBody.Part> filesToMultipartBodyParts(Map<LocalMediaWithState,File> files, Map<LocalMediaWithState,ProgressRequestBody.UploadCallbacks> callbacks) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        files.entrySet();
        ProgressRequestBody.UploadCallbacks callback = null;
        for(Map.Entry<LocalMediaWithState,File> entry: files.entrySet())
        {
            callback = callbacks.get(entry.getKey());
            ProgressRequestBody progressRequestBody =
                    new ProgressRequestBody(entry.getValue(),MediaType.parse("image/png"),entry.getValue().getName(),callback);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", entry.getValue().getName(), progressRequestBody);
            parts.add(part);
        }
        return parts;
    }


    public static RequestBody convertToRequestBody(String param) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
        return requestBody;
    }

    static class AdApiInterceptor implements Interceptor {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            RequestBody requestBody = chain.request().body();
            if (requestBody != null) {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(charset);
                }
                if (requestBody instanceof FormBody) {
                    FormBody.Builder newFormBody = new FormBody.Builder();
                    FormBody oidFormBody = (FormBody) requestBody;

                    for (int i = 0; i < oidFormBody.size(); i++) {
                        newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i));
                    }
                    builder.method(chain.request().method(), newFormBody.build());
                }
            } else {
                URL url = new URL(chain.request().url().toString());
                builder.method(chain.request().method(), chain.request().body());
                builder.url(url);
            }

            Request newRequest = builder.build();
            Response response = chain.proceed(newRequest);
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(Charset.forName("UTF-8"));
            }
            String content = buffer.clone().readString(charset);
            Log.i("cmsApi",String.format("接收响应: [%s] %n返回json:【%s】 %n%s",
                    response.request().url(),
                    content,
                    response.headers()));
            return response;
        }
    }

}